package com.botarena.server.helper;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class Upload {
	private static final Logger log = Logger.getLogger(Upload.class.getName());

	private Map<String, String> fields;
	private Map<String, ByteArrayOutputStream> files;

	public Upload(HttpServletRequest request) throws FileUploadException,
			IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload fileUpload = new ServletFileUpload(factory);

		fields = new HashMap<String, String>();
		files = new HashMap<String, ByteArrayOutputStream>();

		FileItemIterator it = fileUpload.getItemIterator(request);

		while (it.hasNext()) {
			FileItemStream item = it.next();

			if (item.isFormField()) {
				String value = getValue(item);
				log.info("Field: " + item.getFieldName() + " value: " + value);
				fields.put(item.getFieldName(), value);
			} else {
				log.info("Field: " + item.getFieldName() + " file: "
						+ item.getName());
				ByteArrayOutputStream bout = readAll(item.openStream());
				files.put(item.getFieldName(), bout);
			}
		}
	}

	public static ByteArrayOutputStream readAll(InputStream stream)
			throws IOException {
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		while (true) {
			int len = stream.read(buffer);
			if (len > 0) {
				bout.write(buffer, 0, len);
			} else {
				break;
			}
		}
		return bout;
	}

	public String getFileContent(String name) {
		return files.get(name).toString();
	}

	public String getField(String name) {
		return fields.get(name);
	}

	public ByteArrayOutputStream getFile(String name) {
		return files.get(name);
	}

	private String getValue(FileItemStream item) throws IOException {
		byte[] buffer = new byte[255];
		int length = item.openStream().read(buffer);

		if (length == -1) {
			return "";
		} else {
			return new String(buffer, 0, length);
		}
	}
}
